
import React, { PureComponent, Component } from 'react';
import { BasicPagination, isInvalidObject, compareNum, TableCustomize, openSuccessModal, openModalMessage, compareString } from '../../../components/TableCustomize'
import { Row, Col, Form, Select, Layout, Upload, Button, InputNumber, Table, Input, Alert, Spin, Modal, Drawer, Divider, Icon, Badge, PageHeader, Tabs, Card } from 'antd';

import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout'
import { withRouter } from 'react-router';
// import * as APIService from '../../../axios/api_yq'
import * as APIService from '../../../axios/api_px'
import * as APIServiceFile from '../../../axios/File'
import { baseUrl } from '../../../config'

import { getBase64, } from '../../../utils/action'
import EditTable from '../../../components/EditRowTable';
import DetailsForm from './Components/DetailsForm'
const { confirm } = Modal;

const FormItem = Form.Item;
const { Header, Footer, Sider, Content } = Layout;
const { Option } = Select


class Bottomhole extends Component {
    state = {
        type: '三大板下孔等高检测标准',
        dataSource: [],
        dataSource1: [],
        dataSource2: [],
        dataSource3: [],
        modelData: [],
        modelColumns: [
            {
                title: '序号',
                dataIndex: 'number',
                width: 50,
                align: 'center',
                render: (text, record, index) =>
                    <div>
                        {index + 1}
                    </div>
            },
            {
                title: '机型',
                dataIndex: 'code',
                width: 100,
            },
        ],
        clickSaveFlag: false,
        columns: [
            {
                title: '序号',
                dataIndex: 'number',
                width: 50,
                align: 'center',
                ellipsis: true,
                render: (text, record, index) =>
                    <div>
                        {index + 1}
                    </div>
            },
            {
                title: '测量位置',
                dataIndex: 'measuringPoint',
                sorter: (a, b) => compareString(a.measuringPoint, b.measuringPoint),
                width: 100,
                ellipsis: true,
                editable: true,
                required: true,
            },
            {
                title: '要求标准',
                dataIndex: 'standard',
                sorter: (a, b) => compareString(a.standard, b.standard),
                width: 150,
                ellipsis: true,
                editable: true,
                required: true,
            },
            {
                title: '测量点a',
                dataIndex: 'message1',
                sorter: (a, b) => compareString(a.message1, b.message1),
                width: 200,
                ellipsis: true,
            },
            {
                title: '测量点b',
                dataIndex: 'message2',
                sorter: (a, b) => compareString(a.message2, b.message2),
                width: 200,
                ellipsis: true,
            },
            {
                title: '操作',
                dataIndex: 'opts',
                render: (text, record) => {
                    const { editingKey, clickSaveFlag } = this.state;
                    const editable = record.id === editingKey;
                    return editable ? (
                        <span>
                            <a
                                disabled={clickSaveFlag}
                                onClick={() => {
                                    this.handleSave(record)
                                }}
                                style={{ marginRight: 8 }}
                            >
                                保存
                            </a>
                            <Divider type='vertical' />
                            <a onClick={() => this.cancel()}>取消</a>
                        </span>
                    ) : (
                        <span>
                            <a disabled={editingKey !== ''} onClick={() => this.edit(record.id)}>
                                编辑
                            </a>
                            <Divider type='vertical' />
                            <a disabled={editingKey !== ''} onClick={() => this.handleDelete(record)}>
                                删除
                            </a>
                        </span>
                    );
                }
            },
        ],
        formData: {},
        loading: true,
        spinning: false,
        editingKey: '',
        previewVisible: false,
        previewImage: '',
        file: {
            imgId: '',
            imgName: '',
            imgUrl: '',
        },
        fileData: {},
        visible: false,
        selectedRows: [],
        selectedRowKeys: [],
        isAdd: false,
        newData: {}
    }
    componentDidMount() {
        this.queryProductModel()
        this.queryFormModel()
        this.fetch();
        this.queryImg()
    }
    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    //初始化数据
    fetch = (pageNum = 1, pageSize = 1000) => {
        this.setState({ loading: true })
        let searchItem = { pageNum, pageSize }
        APIService.queryThreePlatesStandard(searchItem).then((item) => {
            if (item.data.code === 200) {
                let dataSource = item.data.data.data, dataSource1 = [], dataSource2 = [], dataSource3 = []
                for (let item of dataSource) {
                    if (item.type == '头板') {
                        dataSource1.push(item)
                    } else if (item.type == '中板') {
                        dataSource2.push(item)
                    } else if (item.type == '尾板') {
                        dataSource3.push(item)
                    }
                }
                this.setState({
                    loading: false,
                    dataSource, dataSource1, dataSource2, dataSource3,
                    editingKey: ''
                })
                console.log('这是初始化数据', item);
            } else {
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 适用机型查询
    queryProductModel = () => {
        APIService.queryProductModel({ "pageNum": 1, "pageSize": 1000 }).then(res => {
            if (res.data.data.code !== 200) {
                openModalMessage('warning', res.data.data.msg)
                return
            }
            this.setState({ modelData: res.data.data.data })
        }).catch(err => {
            openModalMessage('error', err.message)
        })
    }
    // 查询表单基础信息
    queryFormModel = () => {
        APIService.queryFormModel(this.state.type).then(res => {
            if (res.data.data.code !== 200) {
                openModalMessage('warning', res.data.data.msg)
                return
            }
            let formData = {}
            if (res.data.data?.data && res.data.data.data.length > 0) {
                formData = res.data.data.data[0]
            }
            this.setState({ formData })
        }).catch(err => {
            openModalMessage('error', err.message)
        })
    }
    // 表单信息新增/修改
    alterFormModel = () => {
        const { formData, type } = this.state

        this.DetailForm.validateFields((err, values) => {
            if (err) return
            this.setState({ spinning: true })
            console.log(values, formData, 'formData');
            let data = { ...formData, ...values, formName: type }
            APIService.alterFormModel(data).then(res => {
                if (res.data.code !== 200) {
                    openModalMessage('warning', res.data.msg)
                    return
                }
                openSuccessModal(res.data.msg)
                this.setState({ spinning: false }, this.queryFormModel)
            }).catch(err => {
                openModalMessage('error', err.message)
            })
        })
    }
    // 点击选择按钮
    onChoose = () => {
        const { formData } = this.state
        let model = formData.model ? formData.model : ''
        let selectedRowKeys = model.indexOf('、') != -1 ? model.split('、') : []
        this.setState({ visible: true, selectedRowKeys })
    }
    // 选择适用机型弹窗 - 点击保存
    getModelCode = () => {
        const { selectedRowKeys, selectedRows, formData } = this.state
        let model = selectedRowKeys.join('、')
        formData.model = model
        this.setState({ formData, visible: false })
    }
    //新增/编辑接口
    newOrCompile = (value) => {
        if (value.id == '头板' || value.id == '中板' || value.id == '尾板') {
            delete value.id
        }
        console.log(value, 'newOrCompile')
        APIService.alterThreePlatesStandard(value).then((item) => {
            this.setState({ clickSaveFlag: false })
            if (item.data.code === 200) {
                openSuccessModal(item.data.msg)
                this.fetch()
                this.setState({ isAdd: false })
            } else {
                this.setState({
                    buttonLoading: false
                })
                openModalMessage('error', item.data.msg)
            }
        })
    }
    // 删除
    handleDelete = (b) => {
        console.log(b, 'b')
        const then = this
        if (b.id == "头板") {
            const dataSource1 = [...this.state.dataSource1];
            this.setState({ dataSource1: dataSource1.filter(item => item.id !== b.id) });
        } else if (b.id == "中板") {
            const dataSource2 = [...this.state.dataSource2];
            this.setState({ dataSource2: dataSource2.filter(item => item.id !== b.id) });
        } else if (b.id == "尾板") {
            const dataSource3 = [...this.state.dataSource3];
            this.setState({ dataSource3: dataSource3.filter(item => item.id !== b.id) });
        } else {
            let id = `idList= ${[b.id]}`
            confirm({
                title: '确认删除当项吗，这将影响其他数据模块?',
                onOk() {
                    APIService.deleteThreePlatesStandard(id).then((item) => {
                        if (item.data.code === 200) {
                            then.fetch()
                            openSuccessModal('删除成功')
                        } else {
                            openModalMessage('error', item.data.msg)
                        }
                    })
                },
                onCancel() {
                },
            })
        }

    }
    // table上直接修改数据
    loadData = (value, dataSource) => {
        console.log('在表格修改数据后保存的数据:', value, dataSource);
        this.newOrCompile(value)
    }
    // 点击编辑按钮
    edit = (id) => { this.setState({ editingKey: id }); }
    // 点击取消按钮
    cancel = () => {
        const { newData, isAdd } = this.state
        if (isAdd) {
            this.handleDelete(newData)
        }
        this.setState({ editingKey: '', clickSaveFlag: false });
    };
    // 新增行
    handleAdd = (type) => {
        // 头板
        if (type == 1) {
            const { dataSource1 } = this.state;

            const newData = {
                id: '头板',
                type: '头板',
                measuringPoint: ``,
                message1: '',
                message2: '',
                standard: '',
            };
            this.setState({
                dataSource1: [newData, ...dataSource1],
                editingKey: '头板',
                newData,
                isAdd: true
            });
        }
        // 中板
        else if (type == 2) {
            const { dataSource2 } = this.state;

            const newData = {
                id: '中板',
                type: '中板',
                measuringPoint: ``,
                message1: '',
                message2: '',
                standard: '',
            };
            this.setState({
                dataSource2: [newData, ...dataSource2],
                editingKey: '中板',
                newData,
                isAdd: true
            });
        }
        // 尾板
        else if (type == 3) {
            const { dataSource3 } = this.state;

            const newData = {
                id: '尾板',
                type: '尾板',
                measuringPoint: ``,
                message1: '',
                message2: '',
                standard: '',
            };
            this.setState({
                dataSource3: [newData, ...dataSource3],
                editingKey: '尾板',
                newData,
                isAdd: true
            });
        }
    };
    // 保存
    handleSave = (row) => {
        console.log(row, 'row')
        this.setState({ clickSaveFlag: true })
        if (row.type == '头板') {
            this.editTable1.validateFields((err, value) => {
                if (err) {
                    this.setState({ clickSaveFlag: false })
                    return
                }
                this.newOrCompile({ ...row, ...value })
            })
        } else if (row.type == '中板') {
            this.editTable2.validateFields((err, value) => {
                if (err) {
                    this.setState({ clickSaveFlag: false })
                    return
                }
                this.newOrCompile({ ...row, ...value })
            })
        } else if (row.type == '尾板') {
            this.editTable3.validateFields((err, value) => {
                if (err) {
                    this.setState({ clickSaveFlag: false })
                    return
                }
                this.newOrCompile({ ...row, ...value })
            })
        }
    };
    // 选择某一行数据
    chooseRow = record => {
        let flag = true;
        let index = 0;
        this.state.selectedRowKeys.forEach((row, i) => {
            if (row === record.code) {
                flag = false;
                index = i;
            }
        })
        const selectedRowKeys = this.state.selectedRowKeys;
        const selectedRows = this.state.selectedRows;
        if (flag) {
            selectedRowKeys.push(record.code);
            selectedRows.push(record);
        } else {
            selectedRowKeys.splice(index, 1);
            selectedRows.splice(index, 1);
        }
        this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
    };

    // 打开详情页
    openDetails = () => {
        const { dataSource1, dataSource2, dataSource3, formData, type, fileData, file } = this.state
        let data = { title: type + '-表单样式', queryForm: { dataSource1, dataSource2, dataSource3, formData, fileData, file }, path: 'Bottomhole' }
        localStorage.setItem('Bottomhole_Report', JSON.stringify(data))
        this.props.history.push({ pathname: "/Bottomhole_Report", data })

    }
    // 上传图片
    uploadImg = () => {
        const { type, fileData, file } = this.state
        console.log(file, ' file');
        this.setState({ spinning: true })
        this.props.form.validateFields((err, values) => {
            if (err) return
            console.log(values, 'values');
            let value = {}
            value = {
                ...fileData,
                "formName": type,
                "imgId": file.imgId,
                "imgName": values['imgName']
            }
            console.log(value);
            APIService.uploadImg(value).then((item) => {
                if (item.data.code === 200) {
                    openSuccessModal(item.data.msg)
                    this.queryImg()
                } else {
                    openModalMessage('error', item.data.msg)
                }
            })
        })
    }
    // 查询图片信息
    queryImg = () => {
        const { type, file } = this.state
        APIService.queryImg(type).then((res) => {
            if (res.data.data.code === 200) {
                // openSuccessModal(res.data.data.msg)
                let data = res.data.data.data
                let fileData = {}
                for (let item of data) {
                    fileData = item
                    file.imgName = item.imgName
                    file.imgId = item.imgId
                    this.queryFileId(item.imgId, 2)
                }
                this.setState({ fileData, file, spinning: false })
            } else {
                openModalMessage('error', res.data.data.msg)
            }
        })
    }
    // 根据文件ID查询详情
    queryFileId = async (id) => {
        const { file } = this.state
        await APIServiceFile.queryFileId(id).then(res => {
            if (res.data.code != 200) {
                openModalMessage('error', res.data.data.msg)
                return
            }
            let data = res.data.data
            file.imgUrl = data?.tomcatPath
            this.setState({ file })
        })
    }

    // 预览图片
    showPicture = (url) => {
        this.setState({ previewImage: url, previewVisible: true })
    }
    render() {
        const { form: { getFieldDecorator } } = this.props;
        const { isAdd, file, loading, type, spinning, formData, editingKey, modelColumns, modelData, selectedRowKeys, selectedRows, visible, previewVisible, previewImage, columns, dataSource1, dataSource2, dataSource3 } = this.state

        const titleStyle = { fontWeight: 'bold', fontSize: 14 }


        const props = {
            name: 'file',
            action: `${baseUrl}/lw-mes-file/file/uploadFile`,
            // listType: "picture-card",  // 上传格式
            headers: {
                userId: localStorage.getItem('userId'),
                Token: localStorage.getItem('token'),
                // "Content-Type": "multipart/form-data",
            },
            showUploadList: false,   // 是否展示文件列表
            // fileList: fileList,   // 已经上传的展示
            onChange: (info) => {
                this.setState({ spinning: true })
                if (info.file.status !== 'uploading') {
                    console.log(info.file, info.fileList);
                }
                if (info.file.status === 'done') {
                    openSuccessModal(`${info.file.name} 文件上传成功！`);
                    this.setState({
                        file: {
                            imgId: info.file.response.data.id,
                            imgUrl: info.file.response.data?.tomcatPath,
                        }
                    })
                    this.uploadImg()
                } else if (info.file.status === 'error') {
                    openModalMessage('warning', `${info.file.name} 文件上传失败！`);
                    this.setState({ spinning: false })
                }
            },
        }
        const rowSelection = {
            type: 'checkbox',
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys,
                })
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                const keys = [... this.state.selectedRowKeys];
                const rows = [... this.state.selectedRows];
                if (selected) {
                    changeRows.forEach(row => {
                        if (isInvalidObject(keys.find(key => key === row.model))) {
                            keys.push(row.model);
                            rows.push(row);
                        }
                    })
                } else {
                    changeRows.forEach(row => {
                        keys.splice(keys.indexOf(row.model), 1);
                        rows.splice(rows.indexOf(row), 1);
                    })
                }
                this.setState({ selectedRows: rows, selectedRowKeys: keys })
            }
        }
        return (
            <Spin spinning={spinning}>
                <BasicLayoutSearch>
                    <PageHeader
                        style={{ padding: '4px 24px' }}
                        title={type}>
                    </PageHeader>
                </BasicLayoutSearch>
                <Layout className="layout-model">
                    <DetailsForm
                        ref={node => this.DetailForm = node}
                        formData={formData}
                        onAlterFormModel={this.alterFormModel}
                        onChoose={this.onChoose}
                        titleStyle={titleStyle}
                        message="说明：这是一个定制化界面，只允许修改部分数据，如需样式变更，请联系开发人员！页面样式参考《附录4-1 三大板等高精度调整记录》。"
                        openDetails={this.openDetails}
                    />
                </Layout>
                <Layout className="layout-model">
                    <Card
                        title={<div style={titleStyle}>头板（A）</div>}
                        extra={<Button onClick={() => this.handleAdd(1)} icon='plus' type='primary' disabled={editingKey && isAdd ? true : false}>新增检验项</Button>}
                        bordered={false}>
                        <Row gutter={24}>
                            <Col>
                                <EditTable
                                    dataSource={dataSource1}
                                    columns={columns}
                                    ref={node => (this.editTable1 = node)}
                                    rowKey={(record) => record.id}
                                    editingKey={editingKey}
                                    pagination={false}
                                    allowDrafting={true}
                                    allowEditable={this.loadData}
                                    loading={loading}
                                />
                            </Col>
                        </Row>
                    </Card>
                </Layout>
                <Layout className="layout-model">
                    <Card
                        title={<div style={titleStyle}>中板（B）</div>}
                        extra={<Button onClick={() => this.handleAdd(2)} icon='plus' type='primary' disabled={editingKey && isAdd ? true : false}>新增检验项</Button>}
                        bordered={false}>
                        <Row gutter={24}>
                            <Col>
                                <EditTable
                                    dataSource={dataSource2}
                                    columns={columns}
                                    ref={node => (this.editTable2 = node)}
                                    rowKey={(record) => record.id}
                                    editingKey={editingKey}
                                    pagination={false}
                                    allowDrafting={true}
                                    allowEditable={this.loadData}
                                    loading={loading}
                                />
                            </Col>
                        </Row>
                    </Card>
                </Layout>
                <Layout className="layout-model">
                    <Card
                        title={<div style={titleStyle}>尾板（C）</div>}
                        extra={<Button onClick={() => this.handleAdd(3)} icon='plus' type='primary' disabled={editingKey && isAdd ? true : false}>新增检验项</Button>}
                        bordered={false}>
                        <Row gutter={24}>
                            <Col>
                                <EditTable
                                    dataSource={dataSource3}
                                    columns={columns}
                                    ref={node => (this.editTable3 = node)}
                                    rowKey={(record) => record.id}
                                    editingKey={editingKey}
                                    pagination={false}
                                    allowDrafting={true}
                                    allowEditable={this.loadData}
                                    loading={loading}
                                />
                            </Col>
                        </Row>
                    </Card>
                </Layout>
                <Layout className="layout-model">
                    <Card
                        title={<div style={titleStyle}>图片</div>}
                        bordered={false}>
                        <Row gutter={24}>
                            <Col span={7}>
                                <div style={{ height: 200, width: '100%', textAlign: 'center', lineHeight: '200px', border: '1px solid #e8e8e8', color: '#c3c2c2', fontSize: 17 }}>
                                    {
                                        file.imgUrl ?
                                            <img width={'100%'} height={190} src={file.imgUrl} onClick={() => this.showPicture(file.imgUrl)} ></img>
                                            :
                                            <div>请上传图片</div>
                                    }
                                </div>
                                <Form layout='inline'>
                                    <FormItem label='图名'>
                                        {getFieldDecorator('imgName', {
                                            initialValue: file.imgName,
                                            getValueFromEvent: (event) => {
                                                return event.target.value.replace(/\s+/g, "")
                                            },
                                        })(<Input placeholder='请输入图片名称' allowClear onPressEnter={() => this.uploadImg()} />)}
                                    </FormItem>
                                    <FormItem>
                                        <Upload {...props}>
                                            <Button type='primary'>
                                                <Icon type="upload" /> 上传
                                            </Button>
                                        </Upload>
                                    </FormItem>
                                </Form>
                            </Col>
                        </Row>
                    </Card>
                </Layout>

                {/* 选择适用机型 */}
                <Modal
                    title={'选择适用机型'}
                    visible={visible}
                    okText={'提交'}
                    cancelText={'取消'}
                    onOk={this.getModelCode}
                    onCancel={() => this.setState({ visible: false })}
                >
                    <TableCustomize
                        columns={modelColumns}
                        rowKey={(record) => record.code}
                        dataSource={modelData}
                        pagination={false}
                        allowDrafting={true}
                        rowSelection={rowSelection}
                        onRow={(record, rowKey) => ({
                            onClick: this.chooseRow.bind(this, record, rowKey)
                        })}
                    />
                </Modal>

                {/* 预览图片 */}
                <Modal visible={previewVisible} footer={null} onCancel={() => this.setState({ previewVisible: false, previewImage: '' })}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </Spin>
        )
    }
}

export default Form.create()(withRouter(Bottomhole));